package com.yb.xczx.cloud.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.yb.core.enums.RedisConstantEnum;
import com.yb.xczx.cache.manager.api.XczxStringCacheManager;
import com.yb.xczx.cloud.system.entity.Dictionary;
import com.yb.xczx.cloud.system.mapper.DictionaryMapper;
import com.yb.xczx.cloud.system.service.IDictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author 姚兵
 * @since 2023-05-07
 */
@Service
@Slf4j
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements IDictionaryService {


    @Autowired
    XczxStringCacheManager xczxStringCacheManager;
    @Override
    public List listCache() {
        Set<String> members = xczxStringCacheManager.getSet(RedisConstantEnum.System.DICTIONARY.getKey(),String.class);
        if(CollectionUtils.isEmpty(members)){
            log.info("缓存中不存在，从数据库中读取");
            List<Dictionary> dictionaries = this.list();
            this.saveToRedis(dictionaries);
            return dictionaries;
        }

        log.info("从缓存中读取");
        List<Dictionary> dictionaries=new ArrayList<>(members.size());
        members.stream().forEach(item->dictionaries.add(JSONObject.parseObject(item,Dictionary.class)));
        return dictionaries;
    }

    @Override
    public void saveToRedis(List<Dictionary> dictionaryList) {
        try {
            log.info("dictionaryList:{}",dictionaryList);
            xczxStringCacheManager.setSet(RedisConstantEnum.System.DICTIONARY.getKey(),new HashSet<>(dictionaryList));
        }catch (Exception e){
            log.info("e:{}",e);
        }

        log.info("插入完成");
    }
}
